package com.nebula.sirius.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 功能描述: <br>
 * 所属包名: com.nebula.sirius.aspect<br>
 * 创建人　: 白剑<br>
 * 创建时间: 04/13/2018 11:07 Friday<br>
 * 当前版本: 1.0<br>
 * 修改历史: <br>
 * 修改时间　　　　　修改人　　　　　版本变更　　　　　修改说明<br>
 * -----------------------------------------------------<br>
 * <br>
 */
@Aspect
@Component
public class LoggingAspect {

    /**
     * 功能描述: 匹配com.nebula.sirius.controller.web包及其只包中的所有public方法<br>
     * 创建人　: 白剑<br>
     * 创建时间: 2018/04/13 15:22:19<br>
     */
    @Pointcut(value = "execution(public * com.nebula.sirius.controller.web..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void before(JoinPoint joinPoint) {

        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        System.out.println();
        System.out.println("URL: " + request.getRequestURL().toString());
        System.out.println("HTTP_METHOD: " + request.getMethod());
        System.out.println("CLASS_METHOD: " + joinPoint.getSignature().getDeclaringTypeName() +
                "." + joinPoint.getSignature().getName());
        System.out.println("ARGS: " + Arrays.toString(joinPoint.getArgs()));
        System.out.println();
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void afterReturning(Object ret) {
        // System.out.println("处理完请求，返回内容: " + ret);
    }

    @AfterThrowing("webLog()")
    public void afterThrowing(JoinPoint jp) {
        // System.out.println("方法执行异常");
    }

    @After("webLog()")
    public void after(JoinPoint jp) {
        // System.out.println("final增强，方法最后执行");
    }

    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjp) {

        try {
            // Object proceed = pjp.proceed();
            // System.out.println("方法环绕proceed，结果是 :" + proceed);
            return pjp.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }
}
